package cn.rulian.base.auth.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.rulian.base.auth.bo.Resource;
import cn.rulian.base.auth.bo.Role;
import cn.rulian.base.auth.dao.RoleDao;
import cn.rulian.base.auth.vo.RoleVo;
import cn.rulian.base.common.service.BaseService;
import cn.rulian.base.common.util.xx;
import cn.rulian.base.common.vo.Result;

/**
 * 角色管理Service
 */
@Service
@Transactional(readOnly = true)
public class RoleService extends BaseService<Role>
{

	// private final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	EntityManager em;

	@Autowired
	private RoleDao dao;

	@Override
	protected RoleDao getDao()
	{
		return dao;
	}
		
	/**
	 * 查询
	 */
	public Result query(final RoleVo vo)
	{
		Sort sort = new Sort("desc".equals(vo.getOrder())?Direction.DESC:Direction.ASC, vo.getSort()); // 排序
		Pageable pageable = new PageRequest(vo.getPage() - 1, vo.getRows(), sort); // 分页查询条件

		//动态查询对象
		Specification<Role> specification = new Specification<Role>()
		{
			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> cq, CriteriaBuilder cb)
			{
				return buildPredicate(root, cb, vo);
			}
		};

		// 查询
		Page<Role> page = dao.findAll(specification, pageable);
		Result result = Result.getResult(page);


		return result;
	}
	

	/**
	 * 构建查询条件
	 */
	private Predicate buildPredicate(Root<Role> root, CriteriaBuilder cb, RoleVo vo)
	{
		List<Predicate> predicates = new ArrayList<Predicate>();


		return cb.and(predicates.toArray(new Predicate[predicates.size()]));
	}

	
	/**
	 * 查询 Excel数据（不分页）
	 */
	public List<Role> QueryExcelData(final RoleVo vo)
	{
		Sort sort = new Sort("desc".equals(vo.getOrder())?Direction.DESC:Direction.ASC, vo.getSort()); // 排序
		//动态查询对象
		Specification<Role> specification = new Specification<Role>()
		{
			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> cq, CriteriaBuilder cb)
			{
				return buildPredicate(root, cb, vo);
			}
		};

		// 查询
		List<Role> list = dao.findAll(specification, sort);
		return list;
	}


	/**
	 * 构建权限验证map。<br/>
	 * 结构说明，键：权限码，值：角色ID串，以逗号分开，串首尾皆有逗号。如  "role_add":",1,5,8,"
	 */
	public Map<String,String> getAuthMap()
	{
		Map<String,String> map = new HashMap<>();
		
		List<Role> list = dao.findAll();
		if(!xx.isEmpty(list))
		{
			String ids=null;
			for(Role role:list)
			{
				long id = role.getId().longValue();
				List<Resource> reList = role.getResourceList();
				if(!xx.isEmpty(reList))
				{
					for(Resource re:reList)
					{
						String authCode = re.getAuthCode();
						if(!xx.isEmpty(authCode))
						{
							ids = map.get(authCode);
							if(ids==null)
							{
								ids=",";
							}
							map.put(authCode, ids+id+",");
						}
					}
				}
			}
		}
		
		return map;
	}
}
